<template>
  <el-dialog :title="$t('common.operation')" :visible.sync="visibleModal" class="el-dialog-normal">
    <div style="margin-bottom: 80px">
      <!-- <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" label-position="left" label-suffix=":">
        <div class="form-detail whiteBox">
          <div class="form-body">
            <el-row :gutter="20">
              <el-col v-for="(item, index) in columns" :key="index" :xs="24" :sm="item.col" :md="item.col" :lg="item.col" :xl="item.col">
                <FormComponents :item-obj="item" :form="ruleForm" :isedit="isedit" />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form> -->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" inline class="dialog-form-two">
        <el-form-item :label="$t('common.selectWare')" prop="warehouseId">
          <WmsAreaCascader v-model="ruleForm.warehouseId" size="small"></WmsAreaCascader>
        </el-form-item>
        <el-button type="primary" @click="addTags">{{ $t('order.addInst') }}</el-button>
        <!-- <el-form-item label="添加出库指令" prop="InstructionsValue">
          <el-select v-model="InstructionsValue" :placeholder="$t('common.placeholderSelect')">
            <el-option v-for="item in InstructionOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <el-table ref="table" :data="InstructionsList">
        <el-table-column prop="instructions" :label="$t('order.inst')" width="100px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.instructions" :placeholder="$t('common.placeholderSelect')" @change="selectChange(scope.row, scope.$index)">
              <el-option v-for="item in InstructionOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="template" :label="$t('common.temp')" width="120px">
          <template slot-scope="scope">
            <el-link v-if="scope.row.template" type="primary" :href="scope.row.template">
              {{ $t('common.downloadTemp') }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileList" :label="$t('common.fileName')" width="200px">
          <template slot-scope="scope">
            <el-upload v-if="scope.row.template || scope.row.instructions === 'RTVPICKUP'" v-loading="uploadLoading" :file-list="fileList" :auto-upload="true"
              :action="Url" accept=".xlsx,.xls" :data="{ row: scope.row }"
              :on-error="handleUploadError" :on-success="handleUploadSuccess(scope.row)" :headers="headers" style="text-align: left">
              <el-button v-if="!scope.row.files" type="text">{{ $t('common.upload') }}</el-button>
              <el-tooltip v-else class="item" effect="dark" :content="scope.row.fileName" placement="bottom-end">
                <span>{{ filterFileName(scope.row.fileName) }}</span>
              </el-tooltip>
            </el-upload>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" :label="$t('common.remark')">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remarks" :placeholder="$t('common.pleaseInput')"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="operation" :label="$t('common.operation')">
          <template slot-scope="scope">
            <el-button type="text" @click.native.prevent="delTags(scope.$index, InstructionsList)">{{ $t('common.del') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="foot-fixed-total" style="text-align: center; margin-top: 30px">
        <el-button @click="visibleModal = false">{{ $t('common.cancel') }}</el-button>
        <el-button :loading="loading" type="primary" @click="submit('ruleForm')">{{ $t('common.confirm') }}</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from "@/utils/auth";
import FormComponents from "@/components/FormComponents/index.vue";
import { changeStatus, getInstruct } from "@/api/order/index.js";
import WmsAreaCascader from "@/components/WmsAreaCascader";
export default {
  components: { FormComponents, WmsAreaCascader },
  data() {
    return {
      tableData: [],
      ruleForm: {},
      isedit: true,
      loading: false,
      rules: {
        receiverName: [{ required: true, message: "请输入收货人" }],
        receiverPhone: [{ required: true, message: "请输入收货人电话" }],
        receiverDetailAddress: [
          { required: true, message: "请输入收货收货地址" },
        ],
        warehouseId: [{ required: true, message: "请选择仓库" }],
      },
      visibleModal: false,
      warehouseList: [],
      InstructionOptions: [
        {
          label: this.$t('inst.InstructionOptions.LABELING'),
          value: "LABELING",
          fileName: '',
          fileUrl: 'https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx'
        },
        // {
        //   label: "移库",
        //   value: "RELOCATION",
        // },
        {
          label: this.$t('inst.InstructionOptions.CHANGEBOX'),
          value: "CHANGEBOX",
          fileName: '',
          fileUrl: ''
        },
        {
          label: this.$t('inst.InstructionOptions.LABELCHANGE'),
          value: "LABELCHANGE",
          fileName: '',
          fileUrl: 'https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx'
        },
        {
          label: this.$t('inst.InstructionOptions.DSORDER'),
          value: "DSORDER",
          fileName: '',
          fileUrl: 'https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xls/092b9403620e4be797de7e4aa3232713/DS订单拣货标模板.xls'
        },
        {
          label: this.$t('inst.InstructionOptions.RTVPICKUP'),
          value: "RTVPICKUP",
          fileName: '',
          fileUrl: ''
        },
        {
          label: this.$t('inst.InstructionOptions.CHANGEPRODUCT'),
          value: "CHANGEPRODUCT",
          fileName: '',
          fileUrl: ''
        },
        {
          label: this.$t('inst.InstructionOptions.DELIVERYFEE'),
          value: "DELIVERYFEE",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.stockAgeFee'),
          value: "stockAgeFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.warehouseOperationFee'),
          value: "warehouseOperationFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.materialCost'),
          value: "materialCost",
          fileName: "",
          fileUrl: "",
        }
      ],
      InstructionsValue: null,
      InstructionsList: [],
      headers: {
        // Authorization: getToken(),
      },
      uploadLoading: false,
      fileList: [],
      uploadMsg: [],
      Url: "https://recruitr.guanyunart.com/api/recruitr/upload/uploadFile",
      params: {}
    };
  },
  computed: {
    columns() {
      return [
        // { prop: 'receiverName', label: '收货人', type: 'input', col: 8 },
        // { prop: 'receiverPhone', label: '收货人电话', type: 'input', col: 8 },
        // { prop: 'receiverEmail', label: '收货人邮箱', type: 'input', col: 8 },
        // { prop: 'receiverPostCode', label: '邮政编码', type: 'input', col: 8 },
        // { prop: 'receiverProvince', label: '省份', type: 'input', col: 8 },
        // { prop: 'receiverCity', label: '城市', type: 'input', col: 8 },
        // { prop: 'receiverDetailAddress', label: '收货地址', type: 'input', col: 24 }
      ];
    },
  },
  methods: {
    setData(data) {
      const {
        id,
        receiverName,
        receiverPhone,
        receiverEmail,
        receiverPostCode,
        receiverProvince,
        receiverCity,
        receiverDetailAddress,
      } = data;
      this.ruleForm = {
        id,
        receiverName,
        receiverPhone,
        receiverEmail,
        receiverPostCode,
        receiverProvince,
        receiverCity,
        receiverDetailAddress,
      };
      this.visibleModal = true;
      // this.getInstruction(id)
    },
    // getInstruction(id) {
    //   let params = {};
    //   id ? (params.orderId = id) : (params = {});
    //   getInstruct({ ...params }).then((res) => {
    //     if (res.content) {
    //       this.InstructionOptions = res.content;
    //     }
    //   });
    // },
    addTags() {
      this.InstructionsList.push({
        instructions: "",
        title: '',
        template: "",
        files: '',
        fileName: '',
        remarks: '',
      });
    },
    delTags(index, rows) {
      rows.splice(index, 1);
    },
    selectChange(row, index) {
      const url = this.InstructionOptions.find(a => a.value === row.instructions).fileUrl
      if (url) {
        this.$refs.table.tableData[index].template = url
      } else {
        this.$refs.table.tableData[index].template = null
      }
    },
    filterFileName(fileName) {
      const maxLength = 22; // 最大长度，包括省略号
      let truncatedName = fileName;
      if (fileName.length > maxLength) {
        const prefixLength = Math.floor((maxLength - 3) / 2); // 前缀长度
        const suffixLength = maxLength - prefixLength - 3; // 后缀长度
        const prefix = fileName.substr(0, prefixLength);
        const suffix = fileName.substr(fileName.length - suffixLength);
        truncatedName = `${prefix}...${suffix}`;
        return truncatedName
      }
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = this.ruleForm;
          this.loading = true;
          data.status = 1;
          let params = {
            id: data.id,
            status: data.status,
            warehouseId: data.warehouseId[0],
            areaId: data.warehouseId[1],
            instructList: this.$refs.table.tableData
          };
          params.instructList = params.instructList.map(item => {
            const match = this.InstructionOptions.find(option => option.value === item.instructions).label
            console.log('match', match)
            return {
              files: item.files,
              type: item.instructions,
              remarks: item.remarks,
              title: match ? match || match.label : ''
            }
          })
          // console.log('params', params)
          // return
          changeStatus(params)
            .then((res) => {
              this.loading = false;
              this.$message.success(this.$t('common.succcessInfo'));
              this.$emit("success");
              this.visibleModal = false;
            })
            .catch((e) => {
              this.loading = false;
            });
        }
      });
    },
    handleUploadProress(e, file, fileList) {
      this.uploadLoading = true;
    },
    handleUploadSuccess(row) {
      return (response, file, fileList) => {
        // 将上传的文件信息赋值给相应行的对象
        row.fileName = file.name;
        row.files = file.response.data;
      };
    },
    handleUploadError() {
      this.uploadLoading = false;
      this.fileList = [];
      this.$message({
        type: "error",
        message: this.$t('common.failedMsg'),
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-link--inner {
  font-size: 12px;
}
</style>
